package db;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Array;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import cn.com.view.MainFrame;
 
 
public class JDBConnection {
    public Connection conn = null; // 声明Connection对象的实例
    public Statement stmt = null; // 声明Statement对象的实例
    public ResultSet rs = null; // 声明ResultSet对象的实例
    private FileInputStream inputFile;
     
    private  static String dbClassName;//定义保存数据库驱动的变量
    private  static String dbUrl;
    private  static String dbUser;
    private  static String dbPwd;
    private  static JDBConnection  sqlserver;
   
    /**
     * 创建sqlserver连接
     * @return
     */
    public static synchronized JDBConnection getSqlServer(){
    	if(sqlserver == null){
    		 sqlserver = new JDBConnection("sqlserver.properties");
    	}
    	return sqlserver;
		
	}
    /**
     * 插入数据
     * @param startDate
     * @param endDate
     * @return
     */
    public int insterDate(String startDate,String endDate) {
    	int updateCount = 0;
    	if(sqlserver == null){
    		sqlserver =new JDBConnection("sqlserver.properties");
    	}
    	//查出要导入的数据 
    	Vector<Map<String,String>> bankData=sqlserver.getBankData(startDate,endDate);
    	if(bankData.size()>0){
    		OracleConnt oracle=new OracleConnt("oracletype.properties");
    		for (int i = 0; i < bankData.size(); i++) {
    			Map<String, String> rowDate=bankData.get(i);
    			String id=rowDate.get("id");
    			String djh=id;
    			for (int j = 0; j < 8-id.length(); j++) {
    				djh ="0"+djh;
				}
    			System.out.println("单据号"+djh);
    			
    			String zwrq=rowDate.get("zwrq");//日期  rq
    			String rlj_rmyh=rowDate.get("rlj_rmyh");//金额 je
    			String yskm=rowDate.get("yskm");//预算功能科目 yskm
    			String ysjc=rowDate.get("ysjc");//只提取ysjc=4的记录
    			String sql = "insert into z_qtgksr (id,djh,xh,rq,je,skgk,mdgk,ssgk,yskm,ysjc,shbz) values" +
    					"("+id+",'"+djh+"',1,TO_DATE('"+zwrq+"','yyyy-mm-dd'),"+rlj_rmyh+",1,1,1,"+yskm+","+ysjc+",1)";
    			//插入一条数据
    			System.out.println("插入一条数据:"+sql);
    			oracle.executeUpdate(sql);
    			updateCount=i+1;
			}
    	}
    	sqlserver.close();
    	return updateCount;
	}
    
    /**
     * 查询银行记录
     * @return
     */  
    public Vector<Map<String,String>> getBankData(String startDate,String endDate) {
    	String sql = "select * from  receive_ysn_bb_cz_yssr where zwrq between '"+startDate+"' and '"+endDate+"'"+" and ysjc=4 and rlj_rmyh > 0.00 and ywzl=1";
    	if(sqlserver == null){
    		sqlserver =new JDBConnection("sqlserver.properties");
    	}
    	System.out.println("查询银行记录:"+sql);
    	ResultSet result=sqlserver.executeQuery(sql);
    	Vector<Map<String,String>> vector = new Vector<Map<String,String>>();
    	try {
			while(result.next()){
				String id=result.getString("id");
				String zwrq=result.getString("zwrq");//日期  rq
				String rlj_rmyh=result.getString("rlj_rmyh");//金额 je
				String yskm=result.getString("yskm");//预算功能科目 yskm
				String ysjc=result.getString("ysjc"); //只提取ysjc=4的记录
				Map<String,String> mapList = new HashMap<String, String>();
				mapList.put("id", id);
				mapList.put("zwrq", zwrq);
				mapList.put("rlj_rmyh", rlj_rmyh);
				mapList.put("yskm", yskm);
				mapList.put("ysjc", ysjc);
				vector.add(mapList);
			}
			
		} catch (SQLException e) {
			sqlserver.close();
			e.printStackTrace();
		}
		sqlserver.close();
		return vector;
	}
    
    
    public JDBConnection(String propertyFileName) {// 带属性文件名的构造方法
        Properties prop = new Properties();// 属性集合对象
        try {
        	if(inputFile == null){
        		inputFile = new FileInputStream(propertyFileName);
        	}
            prop.load(inputFile);// 将属性文件流装载到Properties对象中
            dbClassName = prop.getProperty("dbClassName");
            dbUrl = prop.getProperty("dbUrl");
            dbUser = prop.getProperty("dbUser");
            dbPwd = prop.getProperty("dbPwd");
            Class.forName(dbClassName);// 1.注册驱动
           // conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);//2.建立与数据库的链接
        } catch (Exception e) {
            System.out.println("属性文件  " + propertyFileName + " 打开失败！");
            JOptionPane.showConfirmDialog(MainFrame.open(), "数据库连接失败！请查看当前路径下是否有（sqlserver.properties属性文件）及参数是否正确", "提示", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
 
           
    }
 
    public JDBConnection() {// 默认的不带参数的构造函数
        try {
            Class.forName(dbClassName);// 1.注册驱动
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
 
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);//2.建立与数据库的链接
        } catch (Exception ee) {
           JOptionPane.showConfirmDialog(new JFrame(), "数据库连接失败！检查配置文件sqlserver.properties参数是否正确", "提示", JOptionPane.ERROR_MESSAGE);
           System.exit(0);
        }
        return conn;
    }
    /*
     * 功能：执行查询语句
     */
    public ResultSet executeQuery(String sql) {
        try { // 捕捉异常
        	
            conn = getConnection();//2.建立与数据库的链接
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,//3.创建语句
                    ResultSet.CONCUR_READ_ONLY);
            rs = stmt.executeQuery(sql);//4.执行查询
            
        } catch (SQLException ex) {
            System.err.println(ex.getMessage()); // 输出异常信息
        }
        return rs; // 返回结果集对象 5.结果处理
    }
 
    /*
     * 功能:执行更新操作
     */
    public int executeUpdate(String sql) {
        int result = 0; // 定义保存返回值的变量
        try { // 捕捉异常
        	conn = getConnection();//2.建立与数据库的链接
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            result = stmt.executeUpdate(sql); // 执行更新操作
        } catch (SQLException ex) {
            result = 0; // 将保存返回值的变量赋值为0
        }
        return result; // 返回保存返回值的变量
    }
 
    /*
     * 功能:关闭数据库的连接
     */
    public void close() {//6.释放资源
        try { // 捕捉异常
            try {
                if (rs != null) { // 当ResultSet对象的实例rs不为空时
                    rs.close(); // 关闭ResultSet对象
                }
            } finally {
                try {
                    if (stmt != null) { // 当Statement对象的实例stmt不为空时
                        stmt.close(); // 关闭Statement对象
                    }
                } finally {
                    if (conn != null) { // 当Connection对象的实例conn不为空时
                        conn.close(); // 关闭Connection对象
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace(System.err); // 输出异常信息
        }
    }
 
}